package com.bankcomm.creditcard.redfriday;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.bankcomm.creditcard.redfriday.utils.HttpClientUtils;

public abstract class BaseActivity extends Activity {
	private static final String TAG = "BaseActivity";
	public final static int INDEX_NUM = 3;
	public final static int INDEX_SUPERMARKET = 0;
	public final static int INDEX_GASSTATION = 1;
	public final static int INDEX_FIFTY = 2;
	private final static String SERVER = "http://222.73.205.159/demo/app/api/?method=";
	public final static String METHOD_GETBYGPS = "getbygps";
	public final static String METHOD_GETBYCITY = "getbycity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	protected void startRequest(String path,
			Map<String, String> requestParameter) {
		StringBuilder tmp = new StringBuilder();
		Set<Entry<String, String>> set = requestParameter.entrySet();
		for (Entry<String, String> entry : set) {
			tmp.append(entry.getKey()).append("=").append(entry.getValue())
					.append("&");
		}
		new Task().execute(path, tmp.toString());
	}

	protected abstract void parseJson(String jsonString);

	protected abstract void refreshView();

	private class Task extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = SERVER + params[0];
			String data = params[1];
			String result = "";
			try {
				result = new String(HttpClientUtils.post(url, null, data),
						"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				Log.e(TAG, "doInBackground: " + e.getMessage());
			}
			return result == null ? "" : result;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			// Log.d(TAG, "onPostExecute: " + result);
			parseJson(result);
			refreshView();
			super.onPostExecute(result);
		}

	}

}
